package com.bugsnag.ohos;

import ohos.app.Context;
import ohos.app.IAbilityManager;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.net.NetManager;
import ohos.rpc.RemoteException;
import ohos.storageinfomgr.StorageInfoManager;

/**
 * ContextExtensions
 *
 * @since 2021-07-05
 */
public class ContextExtensions {
    private ContextExtensions() {
    }

    /**
     * Calls [CommonEventManager.subscribeCommonEvent] but swallows [RemoteException]
     * to avoid terminating the process in rare cases where the registration is unsuccessful.
     *
     * @param subscriber
     * @param logger
     */
    public static void registerReceiverSafe(CommonEventSubscriber subscriber,
                                            Logger logger) {
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException exc) {
            logger.w("Failed to register receiver", exc);
        }
    }

    /**
     * Calls [CommonEventManager.unregisterReceiver] but swallows [RemoteException]
     * to avoid terminating the process in rare cases where the registration is unsuccessful.
     *
     * @param subscriber
     * @param logger
     */
    public static void unregisterReceiverSafe(CommonEventSubscriber subscriber,
                                              Logger logger) {
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
        } catch (RemoteException exc) {
            logger.w("Failed to unregister receiver", exc);
        }
    }

    /**
     * get AbilityManager From
     *
     * @param context
     * @return AbilityManager
     */
    public static IAbilityManager getAbilityManagerFrom(Context context) {
        return context.getAbilityManager();
    }

    /**
     * get NetManager From
     *
     * @param context
     * @return NetManager
     */
    public static NetManager getNetManagerFrom(Context context) {
        return NetManager.getInstance(context);
    }

    /**
     * get StorageManager From
     *
     * @param context
     * @return StorageInfoManager
     */
    public static StorageInfoManager getStorageManagerFrom(Context context) {
        return StorageInfoManager.newInstance(context);
    }
}
